<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true"
        >
          <el-form-item
            label="所属街道"
            prop="townWrap"
          >
            <el-cascader
              ref="myCascader"
              v-model="ruleForm.townWrap"
              :options="options"
              placeholder="请选择所属街道"
              clearable
              @change="change"
            />
          </el-form-item>
          <el-form-item
            label="村名称"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入村名称"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="村主任">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>-->
          <el-form-item
            label="所在位置"
            prop="address"
          >
            <el-input
              v-model="ruleForm.address"
              placeholder="请输入村所在位置"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="人口数"
            prop="population"
          >
            <el-input
              v-model.number="ruleForm.population"
              placeholder="请输入村人口数"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="占地面积"
            prop="footprint"
          >
            <el-input
              v-model="ruleForm.footprint"
              placeholder="请输入村占地面积 单位为平方米"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="村简介"
            prop="introduction"
          >
            <el-input
              v-model="ruleForm.introduction"
              type="textarea"
              placeholder="请输入村简介"
              :rows="10"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="村貌图"
            prop="image"
          >
            <el-upload
              :action="uploadUrl"
              :headers="getAuthHeaders()"
              list-type="picture-card"
              :multiple="true"
              :file-list="ruleForm.image"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              accept=".Webp,.baiBMP,.PCX,.TIF,.GIF,.JPEG,.JPG,.TGA,.EXIF,.FPX,.SVG,.PSD,.CDR,.PCD,.DXF,.UFO,.EPS,.AI,.PNG,.HDRI,.RAW,.WMF,.FLIC,.EMF,.ICO,"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog
              :visible.sync="dialogVisible"
              size="tiny"
            >
              <img
                width="100%"
                :src="dialogImageUrl"
                alt
              >
            </el-dialog>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? '立即创建' : '保存编辑' }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "Form",
  props: {
    id: {},
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  data() {
    return {
      ruleForm: {
        townWrap: "",
        town: "",
        name: "",
        address: "",
        population: "",
        footprint: "",
        introduction: "",
        image: [],
      },
      rules: {
        townWrap: [
          { required: true, message: "请选择所属街道", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入村名称", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入村所在位置", trigger: "blur" },
        ],
        population: [
          { required: true, message: "请输入村人口数", trigger: "blur" },
        ],
        footprint: [
          { required: true, message: "请输入村占地面积", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "请输入村简介", trigger: "blur" },
        ],
        image: [
          { required: false, message: "请上传图片", trigger: "change" },
        ]
      },
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      // fileList: [],
      imgAtt: [],
      createForm: {},
    };
  },
  async created() {
    const res = await this.$http.get(`area?join=town`);
    res.data.forEach((area) => {
      area.value = area.id;
      area.label = area.name;
      area.children = area.town;
      if (area.town.length > 0) {
        area.town.forEach((town) => {
          town.value = town.id;
          town.label = town.name;
        });
      }
    });
    this.options = res.data;
    this.setSelectItem()
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(res, file, fileList) {
      let att = [];
      fileList.forEach((file) =>
        att.push(file.response ? file.response : file)
      );
      console.log(fileList)
      this.imgAtt = att;
    },
    handleRemove(file, fileList) {
      let att = [];
      fileList.forEach((file) =>
        att.push(file.response ? file.response : file)
      );
      this.imgAtt = att;
      console.log(fileList)
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
      this.createForm.image = this.imgAtt;
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/village`, this.createForm)  
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Village" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res =  await this.$http.put(`/village/${this.id}`, this.createForm)
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Village" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`village/${id}?join=town`);
      
      const town = await this.$http.get(`town/${res.data.town.id}?join=area`)

      res.data.townWrap = [town.data.area.id, res.data.town.id]

      res.data.image = this.imgAtt = res.data.image ? res.data.image : []

      this.ruleForm = Object.assign({}, res.data);

      this.change([town.data.area.id, res.data.town.id])

    },
    change(val) {
      this.ruleForm.town = val[1]
    },
    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.options.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.options.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        // else if (this.user.level == 3) {
        //   //村级
        //   this.form.area = this.user.area.id
        // } 
    },

    setQuery() {
      if(this.user.level == 1) {
        this.queryForm.area = this.user.area.id
      } else if(this.user.level == 2) {
        this.queryForm.area = this.user.area.id
        this.queryForm.town = this.user.town.id
      } 
    },
  },
};
</script>
